/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package qrlogin;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

/**
 *
 * @author adee
 */
public class QRLoginImageManager {
    private int width;
    private int height;
    private HashMap<String,QRLoginImage> qrLoginImages;

    private QRLoginServlet servlet;


    private void createTempDirectory(){
        File dir = new File(this.servlet.getServletParameters().getTempDir());
        if (!dir.isDirectory()) dir.mkdir();
        dir = null;
    }

    public QRLoginImageManager(QRLoginServlet servlet) {
        this.width = 150;
        this.height = 150;
        this.qrLoginImages = new HashMap<String, QRLoginImage>();
        this.servlet=servlet;
    }


    public static String loginLinkToDirectory(String loginLink){
         return  loginLink.replace('/', '_');      
    }


    public QRLoginImage getQRLoginImage(String sessionId){
        createTempDirectory();


        if (this.qrLoginImages.containsKey(sessionId))
          return this.qrLoginImages.get(sessionId);
        else {
            QRLoginImage qrImage = new QRLoginImage(width, height, sessionId, servlet);
            this.qrLoginImages.put(sessionId, qrImage);
            return qrImage;
        }
    }

    public void deleteQRLoginImage(String sessionId){
        if (this.qrLoginImages.containsKey(sessionId)) {
          QRLoginImage qrImage =  this.qrLoginImages.get(sessionId);
          qrImage.deleteMe();
          this.qrLoginImages.remove(sessionId);
        }

    }

    public void deleteAll(){
          Set keyset =  this.qrLoginImages.keySet();
          while (keyset.iterator().hasNext()){
              this.deleteQRLoginImage((String) keyset.iterator().next());
          }

    }

}
